package com.security.user.filter;

import com.lambdaworks.crypto.SCryptUtil;
import com.security.user.mapper.UserInfoMapper;
import com.security.user.model.UserInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.util.Base64Utils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author yanggld
 * @Date 2020/3/9-13:40
 */
@Component
@Order(2)
public class BasicAuthenticationFilter extends OncePerRequestFilter {

    @Autowired
    public UserInfoMapper userInfoMapper;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
        throws ServletException, IOException {
        System.out.println("**********认证");

        boolean isAuth = false;
        String authorization = request.getHeader("Authorization");
        if (StringUtils.isNoneBlank(authorization)) {
            String token64 = StringUtils.substringAfter(authorization, "Basic ");
            String token = new String(Base64Utils.decodeFromString(token64));
            String[] items = StringUtils.splitByWholeSeparatorPreserveAllTokens(token, ":");
            String username = items[0];
            String password = items[1];
            UserInfo userInfo = userInfoMapper.findByUsername(username);
            if (userInfo!=null&& SCryptUtil.check(password,userInfo.getPassword())) {
                request.setAttribute("user",userInfo);
                isAuth = true;
                filterChain.doFilter(request,response);
            }
        }
        if (!isAuth) {
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            response.setCharacterEncoding("UTF-8");
            response.setContentType("text/json;charset=utf-8");
            response.getWriter().write("认证身份失败!");
            response.getWriter().flush();
            return;
        }

    }
}
